package com.kvin.paylib;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;

/**
 * Created by Kvin on 2017/6/19.
 */
public class PayPop extends PopupWindow {
    public static final int PAY_ALI = 0;
    public static final int PAY_WECHAT = 1;
    public static final int PAY_UNION = 2;
    private RadioGroup payChoiceGroup;
    private OnChoiceChangedListener mListener;


    private PayPop(Context context) {
        super(context);
        initPop(context);
    }

    public static PayPop getInstance(Context context) {
        return new PayPop(context);
    }

    /**
     * init pop
     *
     * @param context
     */
    private void initPop(Context context) {
        View v = LayoutInflater.from(context).inflate(R.layout.pop_pay, null);
        this.payChoiceGroup = (RadioGroup) v.findViewById(R.id.pay_choice_rg);
        this.payChoiceGroup.setOnCheckedChangeListener(mOnCheckedChangeListener);
        setContentView(v);
        ((RadioButton) this.payChoiceGroup.getChildAt(0)).setChecked(true);

        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        setClippingEnabled(true);
        setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        setBackgroundDrawable(new BitmapDrawable());
        setOutsideTouchable(true);
        setFocusable(true);
    }

    /**
     * get current text
     */
    public String getCurrentText() {
        if (payChoiceGroup == null) return "";
        return ((RadioButton) this.payChoiceGroup.findViewById(this.payChoiceGroup.getCheckedRadioButtonId())).getText().toString();
    }

    public int getCurrentIndex() {
        if (payChoiceGroup == null) return -1;
        return payChoiceGroup.indexOfChild(this.payChoiceGroup.findViewById(this.payChoiceGroup.getCheckedRadioButtonId()));
    }

    public void setOnChoiceChangedListener(OnChoiceChangedListener listener) {
        this.mListener = listener;
    }

    /**
     * on check changed listener
     */
    private RadioGroup.OnCheckedChangeListener mOnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (mListener != null) mListener.onChoiceChanged(group, getCurrentIndex());
        }
    };

    /**
     * show
     */
    public void show(View anchor) {
        showAsDropDown(anchor);
    }

    public void show(View anchor, int gravity) {
        showAtLocation(anchor, gravity, 0, 0);
    }

    public void show(View anchor, int gravity, int xOffset, int yOffset) {
        showAtLocation(anchor, gravity, xOffset, yOffset);
    }
}
